package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 会员登录
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    //使用手机号和验证码登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){

        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取缓存的验证码
        String codeInRedis = jedisPool.getResource().get(telephone+ RedisMessageConstant.SENDTYPE_LOGIN);

        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else{

            //验证码输入正确
            //判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            if(member == null){
                //当前用户不是会员，自动完成注册
                member = new Member();
                member.setPassword("123456");
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }

            //登录成功
            //写入Cookie，跟踪用户
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60 * 60 * 24 * 30);//有效期30天
            response.addCookie(cookie);

            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60*30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
    }

    /*
    * gjx
    * */
    //查询会员信息
    @RequestMapping("/findMember")
    public Result findMember(HttpServletRequest request) {
        try {
            Cookie[] cookies = request.getCookies();
            String telephone=null;
            for (Cookie cookie : cookies) {
                String key = cookie.getName();
                if ("login_member_telephone".equals(key)){
                    telephone = cookie.getValue();
                }
            }
            Member member = this.memberService.findByTelephone(telephone);
            return new Result(true, MessageConstant.QUERY_MEMBER_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_MEMBER_FAIL);
        }
    }

    //根据id修改会员信息
    @RequestMapping("/updateById")
    public Result updateById(@RequestBody Member member) {
        try {
            this.memberService.edit(member);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    //根据id修改电话号码
    @RequestMapping("/updatephoneNumber")
    public Result updatephoneNumber(Integer id, String telephone) {
        try {
            this.memberService.updateTelephoneById(id, telephone);
            return new Result(true, "修改电话成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改电话失败");
        }
    }

    //查询旧密码
    @RequestMapping({"/findOldPassword"})
    public Result findOldPassword(HttpServletRequest request, String oldPassword) {
        try {
            //对前端密码加密
            String password = MD5Utils.md5(oldPassword);
            Cookie[] cookies = request.getCookies();
            String telephone=null;
            for (Cookie cookie : cookies) {
                String key = cookie.getName();
                if ("login_member_telephone".equals(key)){
                    telephone = cookie.getValue();
                }
            }
            Member member = this.memberService.findByTelephone(telephone);
            String password1 = member.getPassword();
            if (password != null && password.equals(password1)){
                return new Result(true,"原密码正确");
            }
            return new Result(false, "原密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "原密码错误");
        }
    }

    //提交新密码
    @RequestMapping({"/updatePassword"})
    public Result updatePassword(HttpServletRequest request,String newpassword) {
        try {
            Cookie[] cookies = request.getCookies();
            String telephone=null;
            for (Cookie cookie : cookies) {
                String key = cookie.getName();
                if ("login_member_telephone".equals(key)){
                    telephone = cookie.getValue();
                }
            }
            //根据电话号码修改密码
            memberService.updatePasswordByTelephone(telephone,newpassword);
            return new Result(true, "密码修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "密码修改错误");
        }
    }
}